package com.my.test.thread.concurrent;

import java.util.concurrent.*;

public class BankWaterService2 extends Thread {

    CyclicBarrier c = new CyclicBarrier(4,this);

    ExecutorService service = Executors.newFixedThreadPool(4);

    ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        int result = 0;
        for (int value : map.values()) {
            result = result + value;
        }
        System.out.println(result);
    }

    private synchronized void count() {
        for (int i = 0; i < 4; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        map.put(Thread.currentThread().getName(), 1);
                        c.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    public static void main(String[] args) {
        BankWaterService2 bs = new BankWaterService2();
        bs.count();
    }


}
